package com.yuan.crawler.proxy.impl;

import com.yuan.crawler.proxy.IPProxy;
import com.yuan.crawler.proxy.ProxyServer;
import com.yuan.util.number.NumUtil;
import com.yuan.util.string.StrUtil;
import com.yuan.util.web.HttpUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;

/**
 * @author YouYuan
 * @version 1.0
 * @date 2018/9/7 09:39
 */
public class FreeProxyServerImpl implements ProxyServer {

    private static final String[] IP_POOL_API_URLS = {
//            "http://www.66ip.cn/nmtq.php?getnum=1&isp=0&anonymoustype=0&start=&ports=&export=&ipaddress=&area=1&proxytype=1&api=66ip",
            "http://www.89ip.cn/tqdl.html?api=1&num=1&port=&address=&isp=",
//            "http://www.xicidaili.com/",
    };

    @Override
    public List<IPProxy> requestNewProxy() {
        List<IPProxy> proxyList = new ArrayList<IPProxy>();
        boolean rs = false;
        for (int i = 0; i < IP_POOL_API_URLS.length; i++) {
            String html = null;
            try {
                html = HttpUtil.httpGet(IP_POOL_API_URLS[i]);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StrUtil.notEmpty(html)) {
                Matcher matcher = ProxyServer.IP_PORT_PATTERN.matcher(html);
                if (matcher.find()) {
                    do {
                        String ipAndPort = matcher.group();
                        String[] split = ipAndPort.split(":");
                        IPProxy ipProxy = new IPProxy();
                        ipProxy.setIp(split[0]);
                        ipProxy.setPort(NumUtil.toInt(split[1]));
                        Calendar instance = Calendar.getInstance();
                        instance.add(Calendar.MINUTE, 10);
                        ipProxy.setExpires(instance.getTime());
                        proxyList.add(ipProxy);
                        rs = true;
                    } while (matcher.find());
                }
            }
            if (rs) {
                // 获取成功之后不再尝试访问其它IP服务
                break;
            }
        }
        return proxyList;
    }

    @Override
    public Double requestBalance() {
        return -1.0;
    }
}
